﻿using System;
using System.Collections.Generic;
using System.Data;
using wojilu.IO;
using wojilu.ORM;

namespace wojilu.Data
{
    internal class SqliteDatabaseChecker : IDatabaseChecker
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(SqliteDatabaseChecker));

        private String _connectionString;
        private List<String> existTables = new List<String>();

        public String ConnectionString
        {
            get { return _connectionString; }
            set { _connectionString = value; }
        }

        public DatabaseType DatabaseType
        {
            get { return DatabaseType.SQLite; }
            set { }
        }

        public void CheckDatabase()
        {
            logger.Info("begin check database");
            if (strUtil.IsNullOrEmpty(_connectionString))
            {
                logger.Info("connection String is empty. begin to create sqlite database and set connection string");
                createDatabaseAndSaveConnectionString();
            }
            else
            {
                String connectionItem = DataFactory.GetDialect(DatabaseType.SQLite).GetConnectionItem(_connectionString, ConnectionItemType.Database);
                if (connectionItem.Contains("|datadirectory|"))
                {
                    connectionItem = connectionItem.GetReplace("|datadirectory|", "/App_Data/");
                }
                connectionItem = PathHelper.Map(connectionItem);
                if (strUtil.IsNullOrEmpty(connectionItem))
                {
                    logger.Info("connection String is found, but database is empty. begin to create sqlite database and set connection string");
                    createDatabaseAndSaveConnectionString();
                }
                else if (!File.Exists(connectionItem))
                {
                    logger.Info("ConnectionString:" + _connectionString);
                    logger.Info("the database [" + connectionItem + "] is not found. begin to create sqlite database and set connection string");
                    DatabaseBuilder.BuildSqliteDb(connectionItem);
                }
            }
        }

        public void CheckTable(MappingClass mapping, String db)
        {
            logger.Info("[sqlite] begin check table");
            IDbConnection connection = DataFactory.GetConnection(_connectionString, this.DatabaseType);
            connection.Open();

            IDbCommand cmd = connection.CreateCommand();
            cmd.CommandText = "select name from sqlite_master where type='table' order by name";

            IDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                existTables.Add(reader[0].ToString());
                logger.Info("table found：" + reader[0].ToString());
            }

            reader.Close();
            existTables = new SqliteTableBuilder().CheckMappingTableIsExist(cmd, db, existTables, mapping);

            connection.Close();

        }

        private void createDatabaseAndSaveConnectionString()
        {
            _connectionString = DatabaseBuilder.ConnectionSqliteStringPrefix + DatabaseBuilder.BuildSqliteDb();
            logger.Info("connection String : " + _connectionString);
            DbConfig.SaveConnectionString(_connectionString);
            logger.Info("the connection String is resetted");
        }



        public List<String> GetTables()
        {
            return existTables;
        }

    }
}
